import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meePet/app/LocalColor.dart';
import 'package:meePet/base/BaseFragment.dart';
import 'package:meePet/bean/FoundTabListData.dart';
import 'package:meePet/utils/ext/SizeExt.dart';
import 'package:meePet/utils/ext/StringExt.dart';
import '../../base/LiveData.dart';
import '../../utils/LogUtils.dart';
import '../../web/WebFragment.dart';
import '../../widgets/KeepAliveWrapper.dart';
import 'FoundFragmentVM.dart';
import 'RoleListFragment.dart';

class FoundFragment extends BaseFragment {
  @override
  State<StatefulWidget> createState() {
    return FoundFragmentState();
  }
}

class FoundFragmentState extends BaseFragmentState<FoundFragment>
    with TickerProviderStateMixin {
  FoundFragmentVM? viewModel = Get.put(FoundFragmentVM(), tag: "");
  List<FoundTab> _tabs = [];
  int _currentPageIndex = 0;
  FoundTab? curTabInfo;
  PageController? _pageController;
  TabController? _tabController;
  bool hasLoadData= false;

  @override
  Widget initView(BuildContext context) {
    viewModel = Get.put(FoundFragmentVM(), tag: "${getClassName(context)}");
    _pageController = PageController(initialPage: _currentPageIndex);
    _tabController = TabController(length: _tabs.length, vsync: this);
    return _rootLayout();
  }

  @override
  void onCreate() {
    observerToRefreshUI();
    if(!hasLoadData){
      hasLoadData=true;
      viewModel?.requestFoundTabData();
    }
    super.onCreate();
  }

  @override
  void onResume() {
    //viewModel?.requestFoundTabData();
    super.onResume();
  }

  ///根布局
  Widget _rootLayout() {
    return Stack(
      children: [
        const SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: DecoratedBox(
              decoration: BoxDecoration(color: Color.fromRGBO(19, 18, 24, 1))),
        ),
        Column(
          children: [
            Padding(
              padding: EdgeInsets.only(
                top: MediaQuery.of(context).padding.top/2,
                bottom: 0,
              ),
              child: _searchBar(),
            ),
            _secondTabBar(),
            Expanded(child: _pageView(_tabs)),
          ],
        ),
      ],
    );
  }

  Widget _searchBar() {
    return SizedBox(
      width: double.infinity,
      height: 84.sw(),
      child: Stack(alignment: AlignmentDirectional.bottomCenter, children: [
        Container(
          margin: EdgeInsets.only(left: 20.sw(), right: 20.sw()),
          width: double.infinity,
          height: 40.sw(),
          decoration: BoxDecoration(
              shape: BoxShape.rectangle,
              color: LocalColor.color_32947bff,
              border:
                  Border.all(color: LocalColor.color_b3947bff, width: 1.sw()),
              borderRadius: BorderRadius.all(Radius.circular(20.sw()))),
          child: Row(
            children: [
              Container(
                margin: EdgeInsets.only(left: 13.sw(), right: 3.sw()),
                child: "ic_blue_search".png().loadImageRes(15.sw(), 15.sw()),
              ),
              const Text("搜索人物名称/标签",
                  style: TextStyle(color: Color.fromRGBO(126, 124, 201, 1))),
              Expanded(child: Container(width: 0, height: 1)),
              Container(
                margin: EdgeInsets.only(right: 3.sw()),
                child: "img_btn_search".png().loadImageRes(66.sw(), 33.sw()),
              )
            ],
          ),
        ),
      ]),
    );
  }

  Widget _secondTabBar() {
    return Container(
      margin: EdgeInsets.only(left: 20.sw(), top: 12.sw()),
      height: 40.sw(),
      child: TabBar(
        isScrollable: true,
        labelPadding: EdgeInsets.zero,
        tabAlignment: TabAlignment.center,
        tabs: _getTabItems(),
        onTap: _onTap,
        controller: _tabController,
        indicator: BoxDecoration(color: Colors.transparent),
        dividerHeight: 0.0,
      ),
    );
  }

  List<Widget> _getTabItems() {
    List<Widget> viewList = [];
    _tabs.forEach((item) {
      viewList.add(_getTabView(item));
    });
    return viewList;
  }

  Widget _getTabView(FoundTab info) {
    if (info.alias == curTabInfo?.alias) {
      return getSelectTabView(info);
    } else {
      return getUnSelectedTabView(info);
    }
  }

  Widget getSelectTabView(FoundTab info) {
    return SizedBox(
      height: null,
      width: null,
      child: Container(
        alignment: Alignment.center,
        height: 28.sw(),
        width: null,
        decoration: BoxDecoration(
            shape: BoxShape.rectangle,
            color: LocalColor.color_32947bff,
            borderRadius: BorderRadius.all(Radius.circular(20.sw()))),
        padding: EdgeInsets.only(left: 10.sw(), right: 10.sw()),
        child: Text(
          info.name.orEmpty(),
          style: TextStyle(color: LocalColor.colorWhite, fontSize: 14.sp()),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  Widget getUnSelectedTabView(FoundTab info) {
    return SizedBox(
        height: null,
        width: null,
        child: Container(
          alignment: Alignment.center,
          height: 28.sw(),
          width: null,
          padding: EdgeInsets.only(left: 14.sw(), right: 14.sw()),
          child: Text(info.name.orEmpty(),
              style: TextStyle(
                  color: LocalColor.color_b3C3C2FF, fontSize: 14.sp())),
        ));
  }

  PageView _pageView(List<FoundTab> tabs) {
    return PageView.builder(
      onPageChanged: _pageChange,
      controller: _pageController,
      physics: const AlwaysScrollableScrollPhysics(),
      itemBuilder: (BuildContext context, int index) {
        return _getFragmentByTabId(tabs[index]);
      },
      itemCount: _tabs.length,
    );
  }

  Widget _getFragmentByTabId(FoundTab tab) {
    Widget mFragment = KeepAliveWrapper(child: RoleListFragment(tab));
    LogUtils.i("ruleType是啥：${tab.ruleType}");
    if (tab.ruleType == 3) {
      LogUtils.i("web页面");
      String mUrl = tab.url.orEmpty();
      LogUtils.i("要加载的url是啥：" + mUrl);
      mFragment = KeepAliveWrapper(child: WebFragment(mUrl));
    } else {
      LogUtils.i("原生页面");
      mFragment = KeepAliveWrapper(child: RoleListFragment(tab));
    }

    return mFragment;
  }

  void observerToRefreshUI() {
    viewModel?.tabLd.addObserver(LiveListener(change: (List<FoundTab>? it) {
      if (it != null) {
        LogUtils.i("监听的数据:" + it.toString());
        _tabs = it;
        _setSelectItem(0);
        _refreshUI();
      }
    }));

    LogUtils.i("页面可见，更新数据:");
  }

  void _setSelectItem(int index) {
    _onTap(index, autoRefresh: false);
    _pageChange(index, autoRefresh: false);
  }

  /// bottomnaviagtionbar 和 pageview 的联动
  void _onTap(int index, {bool? autoRefresh = false}) {
    /// 过pageview的pagecontroller的animateToPage方法可以跳转
    _pageController?.jumpToPage(index);
    if (_currentPageIndex != index) {
      _currentPageIndex = index;
    }
    curTabInfo = _tabs[_currentPageIndex];
    if (autoRefresh == true) {
      _refreshUI();
    }
  }

  void _pageChange(int index, {bool? autoRefresh = true}) {
    _tabController?.animateTo(index, duration: Duration(milliseconds: 0));
    if (_currentPageIndex != index) {
      _currentPageIndex = index;
    }
    curTabInfo = _tabs[_currentPageIndex];
    if (autoRefresh == true) {
      _refreshUI();
    }
  }

  void _refreshUI() {
    LogUtils.d("setState刷新UI");
    setState(() {});
  }
}
